// pages/SuSong/clientPro/clientPro.js
import request from '../../../utils/config.js';
import util from '../../../utils/util.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    custInfo: {},
    recordList: new Array(),
    current: 0,
    signRecords:[],
    selfSign:{},
    linkmanList:[],
    isSign:"N",
    canEdit_info:false,
    showEdit:false,
    edit_item:{},
    linkmanEdit:{},
    edit_linkman:false,
    custId:"",
    showModel:false,
    showHomeBtn:false
  },
  goSignDetails: function (e) {
    console.log(e)
    app.globalData.signInfo = e.currentTarget.dataset.info
    wx.navigateTo({
      url: '../signDetails/signDetails',
    })
  },
  edit:function(e){
    let edit_item = e.currentTarget.dataset.info;
    console.log(edit_item)
    if (util.timetrans(edit_item.recordTime, 'day') == util.timetrans(new Date(), 'day')) {
      this.setData({ showEdit: true, edit_value: edit_item.recordDesc, edit_item})
    }
  },
  editInfo:function(){
    wx.navigateTo({
      url: '../addCust/addCust?isEdit=Y',
    })
  },
  cancle: function (e) {
    this.setData({ showEdit: false})
  },
  confirm:function(e){
    let edit_value = this.data.edit_value;
    if (!edit_value) {
      wx.showToast({
        title: '请输入描述',
        icon: 'none',
      })
      return;
    }
    let info = this.data.custInfo;
    let _this = this;
    wx.showLoading({ title: '加载中', mask: true })
    request.requestMisApi('put', "custs/" + info.custVo.custId + "/devRecords/" + this.data.edit_item.id, edit_value, (res) => {
      console.log("成功=", res);
      wx.hideLoading()
      if (res.code == '00') {
        _this.setData({ showEdit: false });
        _this.queryDevRecord()
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("失败=", res)
    });
  },
  //点击显示
  addClientMsg: function() {
    wx.navigateTo({
      url: '../choose/choose?isSign=' + (this.data.inSign),
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.custId) {
      this.setData({
        showHomeBtn:true,
        custId: options.custId
      });
    }
  },

  onShow: function () {
    if (!wx.getStorageSync('token')){
      //未登录
      wx.showModal({
        title: '未登录',
        content: '请先登录系统',
        confirmText: '前去登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    //判断案件进入的场景（列表进入、推送消息进入）
    if (app.globalData.userInfo && !this.data.custId) {//列表进入
      this.setData({ ROLE_CustomInfoManage: app.globalData.loginUserInfo.roles.includes('ROLE_CustomInfoManage') ? true : false })
      this.queryDetail();
    } else {//消息推送
      let _that = this;
      if (!app.globalData.userInfo) {//判断是否登录过
        app.getAuthUserInfo((res) => {
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          _that.getOpenid(_that);
        }, (res) => {
          _that.setData({
            showModel: true
          })
        });
      } else {//已登录
        this.setData({ ROLE_CustomInfoManage: app.globalData.loginUserInfo.roles.includes('ROLE_CustomInfoManage') ? true : false })
        app.globalData.custId = this.data.custId;
        this.queryDetail();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
    this.homeBtn = this.selectComponent("#homeBtn");
  },


  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    that.getOpenid(that);
  },

  //点击返回首页组件回调
  _goHomeBtn: function (e) {
    wx.setStorageSync("flagName", "lawsuitInvest");
    wx.redirectTo({
      url: '../ssIndex/ssIndex?flagName=lawsuitInvest'
    })
  },

  //获取openid
  getOpenid: (_that) => {
    app.getGlobalOpenid(function (token) {
      console.log("检测token===", token)
      if (token) {
        //开始校验看token值
        _that.checkToken();
      } else {
        wx.hideLoading();
        //未登录
        wx.showModal({
          title: '未登录',
          content: '请先登录系统',
          confirmText:'前去登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
      }
    });
  },

  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
        wx.showModal({
          title: '对不起',
          content: '您的权限不足',
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }

      //校验上次记住的部门权限是否还存在
      if (jurisdiction.indexOf(roleQuanxian) < 0) {
        wx.showModal({
          title: '对不起',
          content: "您的" + department + "权限不足",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      app.globalData.custId = _that.data.custId;
      _that.setData({ ROLE_CustomInfoManage: app.globalData.loginUserInfo.roles.includes('ROLE_CustomInfoManage') ? true : false })
      _that.queryDetail();
    }, function (res) {
      //登录超时
      wx.showModal({
        title: '登录超时',
        content: '点击确定重新登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },


  queryDetail: function () {
    let _this = this;
    wx.showLoading({ title: '加载中' })
    request.requestMisApi('get', "custs/" + app.globalData.custId, {}, (res) => {
      let resInfo = JSON.parse(res.body)
      console.log("查询客户详情成功=", resInfo);
      let canEdit_info = false;
      if (util.timetrans(resInfo.custVo.createTime, 'day') == util.timetrans(new Date(), 'day')) {
        canEdit_info = true;
      }
      resInfo.custVo.img = (resInfo.custVo.grade == 3) ? 'stateA.png' : (resInfo.custVo.grade == 2) ? 'stateB.png' : (resInfo.custVo.grade == 1) ? 'stateC.png' : 'state0.png';
      app.globalData.custInfo = resInfo;
      _this.setData({
        canEdit_info, custInfo: resInfo, linkmanList: resInfo.linkmanList
      });
      wx.hideLoading()
      _this.queryDevRecord()
    }, (res) => {
      _this.queryDevRecord()
      wx.hideLoading()
      console.log("查询客户详情失败=", res)
    });
  },
  
  //拨打电话
  callPhone: function (e) {
    let pho = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: pho
    })
  },

  clickTab1: function() {
    this.setData({
      current: 0 
    })
  },
  clickTab2: function () {
    this.setData({
      current: 1
    })
  },
  clickTab3: function () {
    this.setData({
      current: 2
    })
  },

  swiperChange: function (e) {
    // console.log(e)
    if (e.detail.source == "touch") {
      this.setData({ current: e.detail.current })
    }
  },
  
  //开始查询客户交往记录
  queryDevRecord: function(){
    let info = this.data.custInfo;
    let bodyInfo ={
      custId: info.custVo.custId
    }
    let _this = this;
    wx.showLoading({ title: '加载中' })
    request.requestMisApi('get', "custs/" + info.custVo.custId+"/devRecords", bodyInfo, (res) => {
      console.log("查询客户交往记录成功=", res);
      let recordList = JSON.parse(res.body).reverse();
      recordList.forEach(function(e){
        let monthDate = util.timetrans(e.recordTime, "day");
        e.monthDate = monthDate.substring(5, 10)
        e.dayHM = util.timetrans(e.recordTime, "timeHM");
      });
      _this.setData({
        recordList
      });
      wx.hideLoading()
      _this.getSignRecords()
    }, (res) => {
      _this.getSignRecords()
      wx.hideLoading()
      console.log("查询客户交往记录失败=", res)
    });
  },
  getSignRecords:function(){
    let info = this.data.custInfo.custVo;
    let bodyInfo = {
      custId: info.custId
    }
    let _this = this;
    wx.showLoading({ title: '加载中' })
    request.requestMisApi('get', "saleSignRecords", bodyInfo, (res) => {
      wx.hideLoading()
      console.log("查询签到成功=", JSON.parse(res.body));
      let signRecords = JSON.parse(res.body), selfSign = {}, inSign="N";
      signRecords.forEach(function (item) {
        item.signTimeStr = util.filter.dateNum(item.signTime) +' '+ util.timetrans(item.signTime, 'timeHM');
        item.statusStr = util.filter.signStatus(item.status);
        item.signReasonStr = util.filter.signReason(item.signReasonId);
        item.weekDate = util.filter.getWeek(item.signTime) +' '+ util.timetrans(item.signTime, 'day');
        item.useTimeStr = util.filter.getTimeLength(item.useTime/1000);
        if (item.images) {
          item.imagesArr = item.images.split('&&')
        } else {
          item.imagesArr = []
        }
      });
      for (let i = 0; i < signRecords.length; i++) {
        if (app.globalData.operId == signRecords[i].operId && signRecords[i].status == 1){
          inSign = "Y"
          selfSign = signRecords[i];
          break;
        }
      }
      _this.setData({
        signRecords, selfSign,inSign
      });
    }, (res) => {
      wx.hideLoading()
      console.log("查询签到失败=", res)
    });
  },
  isSignOut:function(){
    let _this=this;
    wx.showModal({
      title: '提示',
      content: '是否确认签退？',
      success: function (res) {
        if (res.confirm) {
          _this.getNowAddress()
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  getNowAddress: function () {
    let _this = this;
    wx.showLoading({ title: '加载中', mask: true })
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        _this.setData({
          nowlatitude: res.latitude,
          nowlongitude: res.longitude,
        })
        _this.signOut(res.latitude, res.longitude)
      },
      fail: function (res) {
        wx.showLoading({ title: '加载中', mask: true })
        wx.showModal({
          title: '小程序需要你的允许才能正常使用',
          content: '请点击"去设置"并启用"地理位置",然后确定即可正常使用',
          confirmText: '去设置',
          confirmColor: '#35ca14',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  _this.getNowAddress()
                }
              })
            }
          }
        })
      }
    })
  },
  signOut: function (latitude, longitude){
    let selfSign = this.data.selfSign;
    let _this = this;
    request.requestMisApi('put', "saleSignRecords/" + selfSign.id, {
      signOutDist: util.SYT_util.getGreatCircleDistance(selfSign.latitude, selfSign.longitude, latitude, longitude)
    }, (res) => {
      console.log("签退成功=", res);
      wx.hideLoading()
      if (res.code == '00') {
        wx.showToast({
          title: '签退成功',
          icon: 'success',
        })
        setTimeout(() => {
          _this.goXscg()
        },1000)
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("签退失败=", res)
    });
  },
  //客户联系人编辑
  linkmanEdit: function (e) {
    if (!this.data.ROLE_CustomInfoManage){
      return
    }
    let linkmanEdit = e.currentTarget.dataset.linkman;
    let This=this;
    wx.showActionSheet({
      itemList: ['编辑', '删除'],
      success: function (res) {
        let tapIndex = res.tapIndex;
        This.setData({ linkmanEdit})
        if (tapIndex==0){
          This.setData({ edit_linkman:true})
        }else if (tapIndex==1){
          wx.showModal({
            title: '是否确定删除 ' + linkmanEdit.linkman+' ？',
            success: function (res) {
              if (res.confirm) {
                wx.showLoading({ title: '加载中', mask: true })
                request.requestMisApi('delete', '/custs/customLinkman/' + linkmanEdit.id, {}, function (res) {
                  wx.hideLoading()
                  if (res.code == '00') {
                    This.queryDetail();
                  } else {
                    wx.showToast({
                      title: res.msg,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }, function (err) {
                  wx.showToast({
                    title: '删除失败',
                    icon: 'none',
                    duration: 2000
                  })
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  edit_linkman_ok:function(){
    let This = this, linkmanEdit = this.data.linkmanEdit;
    wx.showLoading({ title: '加载中', mask: true })
    request.requestMisApi('put', '/custs/' + linkmanEdit.custId + '/customLinkman/' + linkmanEdit.id, {
      custName: linkmanEdit.custName,
      linkman: linkmanEdit.linkman,
      tel: linkmanEdit.tel,
    }, function (res) {
      wx.hideLoading()
      if (res.code == '00') {
        This.queryDetail();
        This.setData({edit_linkman:false});
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, function (err) {
      wx.showToast({
        title: '修改失败',
        icon: 'none',
        duration: 2000
      })
    })
  },
  edit_linkman_no: function () {
    this.setData({ edit_linkman:false})
  },
  //点击去销售成果
  goXscg: function () {
    let info = this.data.custInfo;
    info.custVo.statusFlag = "xscg";
    app.globalData.custInfo = info;
    wx.navigateTo({
      url: '../addCollection/addCollection?info=' + JSON.stringify(info),
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  edit_valueinput:function(e){
    this.setData({
      edit_value: e.detail.value
    });
  },
  input_linkman: function (e) {
    let linkmanEdit = this.data.linkmanEdit;
    linkmanEdit.linkman = e.detail.value
    this.setData({ linkmanEdit});
  },
  input_tel: function (e) {
    let linkmanEdit = this.data.linkmanEdit;
    linkmanEdit.tel = e.detail.value
    this.setData({ linkmanEdit });
  },
  //点击收藏
  collect: function (e) {
    let info = this.data.custInfo;
    let _this = this;
    if (info.custVo.isFavor == "Y"){
      request.requestMisApi('delete', "favorCusts/" + info.custVo.custId, { custId: info.custId }, (res) => {
        console.log("取消收藏成功=", res);
        info.custVo.isFavor = "N";
        app.globalData.custInfo = info;
        _this.setData({
          custInfo: info
        });
      }, (res) => {
        wx.hideLoading()
        console.log("取消收藏失败=", res)
      });
    } else if (info.custVo.isFavor == "N"){
      request.requestMisApi('post', "favorCusts/" + info.custVo.custId, { custId: info.custId }, (res) => {
        console.log("收藏成功=", res);
        info.custVo.isFavor = "Y";
        app.globalData.custInfo = info;
        _this.setData({
          custInfo: info
        });
      }, (res) => {
        wx.hideLoading()
        console.log("收藏失败=", res)
      });
    }
    
  },
  //拨打电话
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.queryDetail()
    setTimeout(() => { 
      wx.stopPullDownRefresh();
      wx.showToast({
        icon: 'success',
        duration: 500
      })
    },500)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  // //转发
  // onShareAppMessage: function (res) {
  //   if (res.from === 'button') {
  //     // 来自页面内转发按钮
  //     console.log("来自页面内的转发", res.target)
  //   }
  //   let This = this;
  //   return {
  //     title: "转发测试",
  //     path: 'pages/SuSong/clientPro/clientPro?custId=' + app.globalData.custId,

  //     success: function (res) {
  //       // 转发成功
  //       console.log("转发成功返回数据=", res)
  //       wx.showShareMenu({
  //         // 要求小程序返回分享目标信息
  //         withShareTicket: true
  //       });

  //       if (res.shareTickets) {
  //         // 获取转发详细信息
  //         wx.getShareInfo({
  //           shareTicket: res.shareTickets[0],
  //           success(res) {

  //           },
  //           fail() { },
  //           complete() { }
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     },
  //     complete: function () {

  //     }
  //   }
  // },
})